# coding: utf-8
from celery import shared_task
from services.datamodel.share import stats_logger
from services.datamodel.absorbed.models import mm_AllData, mm_NoteServersMessage
from services.datamodel.student.models import mm_Student
from datetime import date, timedelta
from django.core.cache import cache
import json
from lib.common import get_api_result
import requests
import datetime


@shared_task(name="statistics_numbser", ignore_result=True, queue='cpubound')
def statistics_numbser():
    today = date.today()
    yesterday = (today - timedelta(days=1)).strftime("%Y-%m-%d")
    ydataObj = mm_AllData.get_or_default(day=yesterday)
    if not ydataObj:
        ydataObj = mm_AllData.create(number_sum=0, day=ydataObj)
    qiantian = (today - timedelta(days=2)).strftime("%Y-%m-%d")
    qdataObj = mm_AllData.get_or_default(day=qiantian)
    if not qdataObj:
        qdataObj = mm_AllData.create(number_sum=0, day=qiantian)
    ydataObj.number_sum = qdataObj.number_sum+ydataObj.number_num
    ydataObj.save()


@shared_task(name="send_w_message", ignore_result=True, queue='cpubound')
def send_w_message():
    rule = {1: 24, 2: 48, 3: 72}
    # 获取用户信息
    user_ids = []
    user_cache = cache.get('all_user_ids')
    url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}".format(
            "wx3af648c742d8be80", "37829be2b13040fcc425b4dfd667092f"
        )
    if not user_cache:
        users = mm_Student.filter(source=13).values("zb_openid")
        for v in users:
            user_ids.append(v['zb_openid'])
        cache.set('all_user_ids', json.dumps(user_ids), 3600*24)
        user_cache = cache.get('all_user_ids')
    resObj = mm_NoteServersMessage.filter(status=1).values("id")
    for v in resObj:
        cache_data = json.loads(cache.get('w_message_'+str(v['id'])))
        if cache.get('send_status_'+str(v['id'])):  # 判断是否发送过一轮
            continue
        # 判断是否是定时发送
        now_time = datetime.datetime.now()
        if cache_data['times']:
            if str(now_time) < cache_data['times']:
                continue
        #  记录本次的发送状态
        cache.set('send_status_'+str(v['id']), 1, 3600*rule[cache_data['rule']])
        # 发送数据  rule[cache_data['rule']]
        retObj = get_api_result(url)
        access_token = retObj.get('access_token', None)
        send_url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={}".format(access_token)
        user_openid = json.loads(user_cache)
        number = 0  # 今日发送人数
        for vs in user_openid:
            data = {
                'touser': vs,
                'template_id': cache_data['tid'],
                "page": "pages/tabBar/first/first?id={}".format(v['id']),
                'miniprogram_state': 'formal',  # developer 开发版，trial 体验版， formal正式版
                # 这个data里面的数据是创建模版的时候固定的参数，每个模版参数不通，根据你自己的模版定 ，格式必须这样传，要不然报字段为空，请求不成功
                'data': json.loads(cache_data['content'])
            }
            res = json.loads(requests.post(url=send_url, data=json.dumps(data)).text)
            if not res['errcode']:
                stats_logger.error("发送失败111111")
                stats_logger.error(json.dumps(res))
                continue
            number += 1
        # 将定时时间置空
        cache_data['times'] = ''
        cache.set('w_message_'+str(v['id']), json.dumps(cache_data), None)
        #  记录发送人数， 今日发送人数，累计发送人数
        # number = len(user_openid)
        mesgObj = mm_NoteServersMessage.get_or_default(id=v['id'])
        mesgObj.today_pushsum = number
        mesgObj.push_sum = mesgObj.push_sum + number
        mesgObj.save()


@shared_task(name="clear_data", ignore_result=True, queue='cpubound')
def clear_data():
    now_time = datetime.datetime.now()
    stats_logger.error("现在是凌晨时间:"+str(now_time))
    mm_NoteServersMessage.update(today_pushsum=0, today_clicksum=0)